# this is a example to visualize returns of t+1 .. t+10 
# after some trigger event occurs.

symbol<- c("URZ")

getSymbols(symbol, adjust=TRUE)

# calculate donchian channel for NOK
DC <- DonchianChannel(lag(cbind(Hi(get(symbol)),Lo(get(symbol)))), n=20)

# mark days when price closes below the low band of DC
breakdown <- eval(Cl(get(symbol))>DC[,"high"])
colnames(breakdown) <- c("breakdown")

# how often did that condition occur?
colSums(breakdown, na.rm=TRUE)

# display only the rows when price closes below DC
get(symbol)[breakdown]

# 10 period return from the current period through 10 periods into the future
tendaysreturn <- lag(ROC(Cl(get(symbol)), 10), -10)[breakdown]

# 1:10 period return from the current period through 1:10 periods into the future
returns <- do.call(cbind, lapply(1:10, function(i) {
  lag(ROC(Cl(get(symbol)), i), -i)[breakdown]
}))
colnames(returns) <- 1:10

# plot boxplot of returns
par(mfrow=c(1,1))
boxplot(as.matrix(returns), range=0)

# plot histograms of returns of all 10 periods
par(mfrow=c(2,5))
for (i in 1:10) {
  hist(returns[,i], main=i, breaks=20, col='blue')
}

# melt data and plot lines after all occurences
molten <- melt(t(as.data.frame(returns)))
ggplot(molten, aes(X1,value)) + geom_line(aes(colour=X2))

